package de.koller.oceanFramework.util;

import de.koller.oceanFramework.OceanException;
import java.io.*;

public class MOut {

	private final BufferedOutputStream out;
	
	public MOut( String file ) {
		this( file, false );
	}
	
	public MOut( String file, boolean tmp ) {
		try {
			File dir = new File( file ).getParentFile();
			if( !dir.exists() )
				dir.mkdirs();
			
			File f = new File( file );
			if( tmp )
				f.deleteOnExit();
			out = new BufferedOutputStream( new FileOutputStream( f ) );
		} catch ( IOException ex ) {
			throw new OceanException( ex );
		}
	}

	public MOut( OutputStream out ) {
		this.out = new BufferedOutputStream( out );
	}
	
	public void write( byte... data ) {
		try {
			out.write( data, 0, data.length );
		} catch ( IOException ex ) {
			throw new OceanException( ex );
		}
	}
	
	public void writeInt( int... data ) {
		for( int i : data )
			write( Bytnig.intToByte( i ) );
	}
	
	public void writeLong( long... data ) {
		for( long i : data )
			write( Bytnig.longToByte( i ) );
	}
	
	public void writeFloat( float... data ) {
		for( float i : data )
			write( Bytnig.floatToByte( i ) );
	}
	
	public void writeDouble( double... data ) {
		for( double i : data )
			write( Bytnig.doubleToByte( i ) );
	}
	
	public void writeString( String... data ) {
		for( String i : data ) {
			byte[] b = i.getBytes();
			writeInt( b.length );
			write( b );
		}
	}
	
	public void writeUTF8String( String... data ) {
		for( String i : data ) {
			byte[] b = null;
			try {
				b = i.getBytes( "latin1" );
			} catch( Exception ex ) {
				throw new OceanException( ex );
			}
			writeInt( b.length );
			write( b );
		}
	}
	
	public void close() {
		try {
			out.flush();
			out.close();
		} catch ( IOException ex ) {
			throw new OceanException( ex );
		}
	}
	
}
